#include "safestr.h"

char *fold(String *s) {
    return s->data;
}

void copy(void *dst, const void *src, unsigned int len) {
    const char *psrc;
    char *pdst;
    unsigned int x;
    for (x = len, psrc = (const char *) src, pdst = (char *) dst; x; psrc++, pdst++, x--) {
        *pdst = *psrc;
    }
}

unsigned int length(const char *src) {
//    int l = (int) strlen(src);
//    printf("strlen: %d\n", l);
//    return l;
    int n;
    const char *p;
    for (n = 0, p = src; *p; p++, n++);
    printf("len by for loop: %d\n", n);
    return n;
}

String *init(const char *src) {
    unsigned int len = length(src);
    unsigned int size = sizeof(struct s_string) + (len + 1);
    String *p = (String *) malloc(size);
    if (p == NULL) {
        perror("malloc\n");
        exit(EXIT_FAILURE);
    }
    *p = (String) {};
    copy(p->data, src, len);
    p->count = len;
    return p;
}

String *concat(String *s, const char *src) {
    unsigned int len = length(src);
    unsigned int size = len + sizeof(struct s_string) + s->count + 1;
    String *new_s = (String *) realloc(s, size);
    if (!new_s) {
        perror("realloc\n");
        return NULL;
    }
    copy(new_s->data + new_s->count, src, len);
    new_s->count += len;
    *(new_s->data + new_s->count) = 0;
    return new_s;
}

